<template>
  <div>
    <Header />
    <div class="container" id="app">
      <div class="content">
        <div class="main">
          <div class="info-content clearfix">
            <div class="user-profile-nav">
              <h1>个人中心</h1>
              <a href="/order" class="orders">我的订单</a>
              <a href="/myinfo" class="profile active">基本信息</a>
            </div>
            <div class="profile-container">
              <div class="profile-title">基本信息</div>
              <div class="avatar-container">
                <div class="avatar-content">
                  <el-upload
                    class="avatar-uploader"
                    action="/api/user/upload"
                    :headers="myHeaders"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                  <div class="tips">仅支持JPG格式,且文件需小于1M</div>
                </div>
              </div>
              <div style="display: grid">
                <el-form
                  :model="ruleForm"
                  :rules="rules"
                  ref="ruleForm"
                  label-width="100px"
                  class="demo-ruleForm"
                >
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="ruleForm.nickname"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" prop="sex">
                    <el-radio v-model="ruleForm.sex" label="男"></el-radio>
                    <el-radio v-model="ruleForm.sex" label="女"></el-radio>
                    <el-radio v-model="ruleForm.sex" label="保密"></el-radio>
                  </el-form-item>
                  <el-form-item label="手机号" prop="phone" required>
                    <el-input v-model="ruleForm.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="居住地" prop="delivery">
                    <el-cascader
                      size="large"
                      :options="options"
                      v-model="ruleForm.city"
                    >
                    </el-cascader>
                  </el-form-item>
                  <el-form-item label="个人简介" prop="introduction">
                    <el-input
                      type="textarea"
                      :rows="5"
                      v-model="ruleForm.introduction"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm('ruleForm')"
                      >保存</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '@/components/Header'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { getUserInfo, updateUserInfo } from '@/api/user'
export default {
  name: 'VueIndex',
  components: { Header },
  data () {
    return {
      imageUrl: '',
      options: regionData,
      myHeaders: { token: localStorage.getItem('token') },
      ruleForm: {
        id: 0,
        nickname: '',
        sex: '男',
        phone: '',
        city: [],
        introduction: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[34578]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur,change'
          }
        ],
        introduction: [
          { required: true, message: '请输入个人简介', trigger: 'blur' },
          { min: 10, max: 50, message: '长度在 10 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  mounted () {
    getUserInfo().then(res => {
      this.user = res.data
      this.ruleForm.id = this.user.id
      this.ruleForm.nickname = this.user.nickname
      this.ruleForm.phone = this.user.phone
      this.ruleForm.city = this.getCityCode(this.user.city)
      this.ruleForm.introduction = this.user.introduction
      this.ruleForm.sex = this.user.sex
      this.imageUrl = this.user.img
    })
  },
  computed: {
    city () {
      let loc = ''
      for (let i = 0; i < this.ruleForm.city.length; i++) {
        loc += CodeToText[this.ruleForm.city[i]]
        if (i !== this.ruleForm.city.length - 1) {
          loc += ' '
        }
      }
      return loc
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.$message.success('上传成功')
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      }
      return isJPG && isLt2M
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = {
            id: this.ruleForm.id,
            nickname: this.ruleForm.nickname,
            phone: this.ruleForm.phone,
            city: this.city,
            introduction: this.ruleForm.introduction,
            sex: this.ruleForm.sex
          }
          updateUserInfo(data).then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          })
        } else {
          this.$message({
            message: '请填写完整信息',
            type: 'warning'
          })
          return false
        }
      })
    },
    getCityCode (cityText) {
      const codeArray = []
      if (cityText != '') {
        // 将字符串每3个放入一个数组中
        const cityArray = this.getCityArr(cityText)
        console.log(cityArray)
        if (cityArray.length == 1) {
          codeArray.push(TextToCode[cityArray[0]].code)
        } else if (cityArray.length == 2) {
          codeArray.push(TextToCode[cityArray[0]].code)
          codeArray.push(TextToCode[cityArray[0]][cityArray[1]].code)
        } else if (cityArray.length == 3) {
          codeArray.push(TextToCode[cityArray[0]].code)
          console.log(cityArray[1])
          codeArray.push(TextToCode[cityArray[0]][cityArray[1]].code)
          codeArray.push(
            TextToCode[cityArray[0]][cityArray[1]][cityArray[2]].code
          )
        }
      }

      return codeArray
    },
    // 将空格形式的字符串分割成数组
    getCityArr (cityText) {
      const cityArray = []
      let city = ''
      for (let i = 0; i < cityText.length; i++) {
        if (cityText[i] != ' ') {
          city += cityText[i]
        } else {
          cityArray.push(city)
          city = ''
        }
      }
      cityArray.push(city)
      return cityArray
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 1200px;
  margin: 0 auto;
}
.content {
  overflow: hidden;
  margin-top: 30px;
}
.main {
  padding: 0 18px;
}
.info-content {
  border: 1px solid #e1e1e1;
  position: relative;
}
.clearfix:after,
.clearfix:before {
  content: " ";
  display: table;
}
.info-content .user-profile-nav {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 200px;
  background-color: #f4f3f4;
  text-align: center;
  border-right: 1px solid #e1e1e1;
}
a {
  text-decoration: none;
}
.info-content .orders-container,
.info-content .profile-container {
  float: left;
  margin-left: 200px;
  padding-left: 40px;
  width: 922px;
  min-height: 900px;
}
.clearfix:after {
  clear: both;
}
.info-content .user-profile-nav h1 {
  margin-top: 40px;
  margin-bottom: 30px;
  font-size: 22px;
  color: #222;
  font-weight: 400;
}
.info-content .user-profile-nav a.active {
  color: #fff;
  background-color: #ed3931;
}
.info-content .user-profile-nav a {
  display: block;
  font-weight: 400;
  color: #333;
  height: 40px;
  width: 202px;
  margin-left: -1px;
  line-height: 40px;
  font-size: 18px;
}
.info-content .orders-container,
.info-content .profile-container {
  float: left;
  margin-left: 200px;
  padding-left: 40px;
  width: 922px;
  min-height: 900px;
}
.info-content .orders-container .profile-title,
.info-content .profile-container .profile-title {
  padding: 26px 0;
  color: #ec443f;
  font-size: 18px;
  border-bottom: 1px solid #e1e1e1;
  margin-bottom: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-container {
  text-align: center;
  float: left;
  color: #333;
  background: #fff;
  width: 270px;
}
.avatar-container .avatar-content img {
  width: 258px;
  height: 258px;
}

img {
  border-style: none;
}
.avatar-container .tips {
  margin-top: 10px;
  color: #999;
  font-size: 18px;
  line-height: 30px;
}
</style>
